package org.simp.handler;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.simp.context.SimpContext;
import org.simp.core.message.SimpMessage;
import org.simp.core.message.SimpMessageWraper;
import org.simp.core.request.SimpRequest;
import org.simp.core.request.SimpRequestWarper;
import org.simp.interceptor.SimpHandlerInterceptor;
import org.simp.router.RouterInterceptor;
import org.simp.session.SimpSession;

/**
 * @author zhuhaitao at 2014-5-23
 *
 * 
 */
public abstract class AbstractSimpHandler extends IoHandlerAdapter implements SimpHandler {

	protected SimpContext context;
	
	protected RouterInterceptor routerInterceptor;
	
	protected SimpHandlerInterceptor simpHandlerInterceptor;

	@Override
	public void init(SimpContext context,RouterInterceptor routerInterceptor ,SimpHandlerInterceptor simpHandlerInterceptor) {
		this.context = context;
		this.routerInterceptor = routerInterceptor;
		this.simpHandlerInterceptor = simpHandlerInterceptor;
	}


	@Override
	public SimpContext getContext() {
		return context;
	}




	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if(message instanceof SimpMessageWraper){
			SimpMessageWraper msg = (SimpMessageWraper) message;
			SimpSession simpSession = getSession(session);
			SimpRequestWarper simpRequest = new SimpRequestWarper(msg, simpSession);
			/**如果收到的消息地址不是当前位置，需要分发**/
			if(routerInterceptor != null && routerInterceptor.dispatchRequest(simpRequest, this)){
			}else{
				receiveMessage(simpRequest);
				simpHandlerInterceptor.receiveRequest(simpRequest, this);
			}
		}
	}


	protected abstract SimpSession getSession(IoSession session) ;

	/**
	 * 收到请求
	 * @param request
	 *  @Author zhuhaitao at 2014年6月25日
	 *
	 */
	protected void receiveMessage(SimpRequest request){
		
	}


	@Override
	public SimpRequest sendAndWaitResponse(SimpMessage message, int seconds) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public SimpRequest sendAndWaitResponse(SimpMessage message) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
}
